<template>
  <div class="app-container" v-loading.fullscreen.lock="upload.isUploading">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="personName">
        <el-input
          v-model="queryParams.personName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="cardId">
        <el-input
          v-model="queryParams.cardId"
          placeholder="请输入身份证号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测时间" prop="detectionTimeStr">
        <el-date-picker
          v-model="detectionTimeStr"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleChangeTime"
        />
      </el-form-item>
      <el-form-item label="检测状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择检测状态">
          <el-option label="已检" :value="1" />
          <el-option label="未检" :disabled="!detectionTimeStr" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="检测结果" prop="detectionResult">
        <el-select
          v-model="queryParams.detectionResult"
          placeholder="请选择检测结果"
        >
          <el-option label="阴" :value="1" />
          <el-option label="阳" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门">
        <el-cascader
          :options="hangye"
          v-model="queryParams.deptId"
          :show-all-levels="false"
          :props="{ checkStrictly: true, emitPath: false, value: 'id' }"
          clearable
          @change="handleChangeDept"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="负责人">
        <el-input
          v-model="chargeName"
          clearable
          size="small"
          placeholder="暂无"
          readonly
        />
      </el-form-item>
      <el-form-item label="类别" prop="detectionCycleId">
        <el-select
          v-model="queryParams.detectionCycleId"
          filterable
          placeholder="请选择类别"
        >
          <el-option
            v-for="item in category"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:ptesting:import']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
      <div
        v-if="showText"
        style="margin-right: 15px; float: right; color: #606266"
      >
        共{{ zong }}人 {{ parseInt(zong - total) }}人已完成 {{ total }}人未完成
      </div>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ptestingList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="姓名" align="center" prop="personName" />
      <el-table-column label="身份证号" align="center" prop="cardId" />
      <el-table-column label="手机号" align="center" prop="phoneNumber" />
      <el-table-column
        label="所属部门"
        align="center"
        prop="deptName"
        width="400"
      />
      <el-table-column
        label="类别"
        align="center"
        prop="detectioncycleName"
        width="120"
      >
        <template slot-scope="{ row }">
          {{
            (row.detectionCycleList &&
              row.detectionCycleList.length > 0 &&
              row.detectionCycleList[0].categoryName) ||
            ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        :label="state === 2 ? '未检时间' : '检测时间'"
        align="center"
        prop="detectionTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.detectionTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测状态" align="center" prop="state">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1">已检</span>
          <span v-if="scope.row.state == 2">未检</span>
        </template>
      </el-table-column>
      <el-table-column label="检测结果" align="center" prop="detectionResult">
        <template slot-scope="scope">
          <span v-if="scope.row.detectionResult == 1">阴性</span>
          <span v-if="scope.row.detectionResult == 2">阳性</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改核酸信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="身份证号" prop="cardId">
          <el-input
            v-model="form.cardId"
            placeholder="请输入身份证号"
            @blur="cardname"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="personName">
          <el-input
            v-model="form.personName"
            placeholder="请输入姓名"
            disabled
          />
        </el-form-item>
        <el-form-item label="检测时间" prop="detectionTimeStr">
          <el-date-picker
            clearable
            size="small"
            v-model="form.detectionTimeStr"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择检测时间"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检测地点" prop="detectionAddress">
          <el-input
            v-model="form.detectionAddress"
            placeholder="请输入检测地点"
          />
        </el-form-item>
        <el-form-item label="检测结果" prop="detectionResult">
          <el-select
            v-model="form.detectionResult"
            placeholder="请选择检测结果"
            style="width: 100%"
          >
            <el-option label="阴" :value="1" />
            <el-option label="阳" :value="2" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="重点人群id" prop="personId">
          <el-input v-model="form.personId" placeholder="请输入重点人群id" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const baseURL = process.env.VUE_APP_BASE_API
import {
  listPtesting,
  getPtesting,
  delPtesting,
  addPtesting,
  updatePtesting,
  exportPtesting,
  nameselect,
  mechanism,
  importTemplate
} from "@/api/control/ptesting";
import { getToken } from "@/utils/auth";
import { getCharge, categorychargelist } from "@/api/control/person";
import { treeselectrole } from "@/api/control/dept";
export default {
  name: "Ptesting",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 核酸信息表格数据
      ptestingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        detectionTime: null,
        detectionAddress: null,
        detectionResult: null,
        organizationId: null,
        personId: null,
        detectionCycleId: null,
        deptId: null,
        cardId: null,
        state: null,
        personName: null,
        detectionResult: null,
      },
      // 表单参数
      form: {
        personName: "",
      },
      // 表单校验
      rules: {},
      detectionTimeStr: null,
      category: [],
      hangye: [],
      chargeName: "",
      state: 1,
      yj: 0,
      wj: 0,
      zong: 0,
      showText: false,
       // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/ptesting/importData",
      },
    };
  },
  created() {
    this.getList();
    this.categorychargeList();
    this.getTreeSelect();
  },
  methods: {
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        window.location.href = baseURL + "/common/download?fileName=" + encodeURI(response.msg) + "&delete=" + true;
        // this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    handleChangeTime(val) {
      console.log(val);
      if (!val && this.queryParams.state === 2) {
        this.queryParams.state = null;
      }
    },
    handleChangeDept(val) {
      if (!val) {
        this.chargeName = "";
      } else {
        getCharge(val).then((res) => {
          if (res.data) {
            this.chargeName = res.data.nickName;
          } else {
            this.chargeName = "";
          }
        });
      }
    },
    // 获取所有部门
    getTreeSelect() {
      treeselectrole().then((res) => {
        res.data.forEach((item) => {
          if (!item.children) {
            item.children = [];
          }
        });
        this.hangye = res.data;
      });
    },
    /** 类别下拉框 */
    categorychargeList() {
      categorychargelist().then((res) => {
        this.category = res.data;
      });
    },
    /** 查询核酸信息列表 */
    getList() {
      this.loading = true;
      if (this.detectionTimeStr) {
        this.queryParams.starTime = this.detectionTimeStr[0];
        this.queryParams.entTime = this.detectionTimeStr[1];
      } else {
        this.queryParams.starTime = null;
        this.queryParams.entTime = null;
      }

      listPtesting(this.queryParams).then((response) => {
        this.state = this.queryParams.state;
        this.ptestingList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.wj = response.wj || 0;
        this.yj = response.yj || 0;
        this.zong = response.zong || 0;
        if (this.queryParams.state === 2) {
          this.showText = true;
        } else {
          this.showText = false;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: "",
        detectionTime: null,
        detectionAddress: null,
        detectionResult: null,
        organizationId: null,
        personId: null,
        createTime: null,
        detectionCycleId: null,
        deptId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.detectionTimeStr) {
        let starTime = this.detectionTimeStr[0];
        let entTime = this.detectionTimeStr[1];
        if (this.queryParams.state === 2 && starTime !== entTime) {
          this.$message({
            type: "warning",
            message: "只能检测当天的未完成状态",
          });
          return;
        }
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.deptId = null;
      this.detectionTimeStr = null;
      this.chargeName = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 身份证号查姓名
    cardname() {
      this.nameselete(this.form.cardId);
    },
    // 姓名下拉框
    nameselete(cardId) {
      nameselect({ cardId: cardId }).then((res) => {
        setTimeout(() => {
          this.$set(this.form, "personName", res.data.personName);
          this.$set(this.form, "personId", res.data.personId);
        }, 0);
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加核酸信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPtesting(id).then((response) => {
        this.form = response.data;
        this.form.detectionTimeStr = response.data.detectionTime;
        this.form.detectionResult = Number(response.data.detectionResult);
        this.open = true;
        this.title = "修改核酸信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form.id);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != "") {
            if (
              this.form.cardId == undefined ||
              this.form.cardId == "" ||
              this.form.cardId == null
            ) {
              this.msgError("身份证号不能为空！");
              return false;
            }
            console.log(this.form.personName);
            if (
              this.form.personName == undefined ||
              this.form.personName == "" ||
              this.form.personName == null
            ) {
              this.msgError("请输入正确的身份证号！");
              return false;
            }
            if (
              this.form.detectionTimeStr == undefined ||
              this.form.detectionTimeStr == "" ||
              this.form.detectionTimeStr == null
            ) {
              this.msgError("检测时间不能为空！");
              return false;
            }
            if (
              this.form.detectionResult == undefined ||
              this.form.detectionResult == "" ||
              this.form.detectionResult == null
            ) {
              this.msgError("检测结果不能为空！");
              return false;
            }
            updatePtesting(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (
              this.form.cardId == undefined ||
              this.form.cardId == "" ||
              this.form.cardId == null
            ) {
              this.msgError("身份证号不能为空！");
              return false;
            }
            console.log(this.form.personName);
            if (
              this.form.personName == undefined ||
              this.form.personName == "" ||
              this.form.personName == null
            ) {
              this.msgError("请输入正确的身份证号！");
              return false;
            }
            if (
              this.form.detectionTimeStr == undefined ||
              this.form.detectionTimeStr == "" ||
              this.form.detectionTimeStr == null
            ) {
              this.msgError("检测时间不能为空！");
              return false;
            }
            if (
              this.form.detectionResult == undefined ||
              this.form.detectionResult == "" ||
              this.form.detectionResult == null
            ) {
              this.msgError("检测结果不能为空！");
              return false;
            }
            addPtesting(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除核酸信息?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delPtesting(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有核酸信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportPtesting(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
